package com.yc.fav.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yc.fav.dao.TagFavMapper;
import com.yc.fav.dao.TagMapper;
import com.yc.fav.entity.Fav;
import com.yc.fav.dao.FavMapper;
import com.yc.fav.entity.Tag;
import com.yc.fav.entity.TagFav;
import com.yc.fav.service.BizException;
import com.yc.fav.service.IFavService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yc.fav.util.MBHelper;
import com.yc.fav.util.Utils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author k
 * @since 2024-10-28
 */
@Service
public class FavServiceImpl extends ServiceImpl<FavMapper, Fav> implements IFavService {
    @Override
    public void create(Fav fav) throws BizException {
    //验证用户输入
        Utils.checkEmpty(fav.getName(),"请输入网址名称",-1);
        Utils.checkEmpty(fav.getAddr(),"请输入网址",-2);
        Utils.checkEmpty(fav.getIntro(),"请输入网址介绍",-3);
        Utils.check(fav.getName().length()<2,"网址名称至少2个字",-4);
        //验证数据库是否有该链接
        Integer count=MBHelper.execute(sqlSession -> {
            FavMapper mapper = sqlSession.getMapper(FavMapper.class);
            LambdaQueryWrapper<Fav> lqw=new LambdaQueryWrapper<>();
            lqw.eq(Fav::getAddr,fav.getAddr());
            lqw.eq(Fav::getUid,fav.getUid());
            return mapper.selectCount(lqw);
        });
        Utils.check(count>0,"该链接已经收藏了",-5);
        //保存记录
        //拆分分类
        List<Tag> tags=new ArrayList<>();
        if(fav.getTags().isBlank()==false){
            String[] items=fav.getTags().split("[,;，：]+");
            for(String item:items){
                Tag tag=new Tag();
                tag.setName(item);
                tag.setUid(fav.getUid());
                tags.add(tag);
            }
        }
        MBHelper.execute(sqlSession -> {
            FavMapper mapper = sqlSession.getMapper(FavMapper.class);
            TagMapper tagMapper = sqlSession.getMapper(TagMapper.class);
            TagFavMapper tagFavMapper = sqlSession.getMapper(TagFavMapper.class);
            mapper.insert(fav);
            for(Tag tag:tags){
                LambdaQueryWrapper<Tag> lqw=new LambdaQueryWrapper<>();
                lqw.eq(Tag::getUid,tag.getUid());
                lqw.eq(Tag::getName,tag.getName());
                Tag dbTag=tagMapper.selectOne(lqw);
                if(dbTag==null){
                    //没有分类，新增
                    tagMapper.insert(tag);
                }else{
                    tag.setId(dbTag.getId());
                }
                TagFav tagFav=new TagFav();
                tagFav.setFid(fav.getId());
                tagFav.setTid(tag.getId());
                tagFavMapper.insert(tagFav);
            }
            return null;
        });
    }
}
